# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import typing as t

from ksai.serializer import JsonSerializable, serialize
from ksai.utils import datetimes


class ApiResponse(JsonSerializable):
    timestamp: int = datetimes.timestamp()
    status: int = 200
    message: str = None
    success: bool = False
    code: t.Optional[int] | t.Optional[str] = "200"
    result: t.Optional[object] = None

    def __init__(self,
                 status: t.Optional[int] = 200,
                 message: t.Optional[str] = None,
                 success: t.Optional[bool] = False,
                 code: t.Optional[int] | t.Optional[str] = "200",
                 result: t.Optional[object] = None):
        self.timestamp = datetimes.timestamp()
        self.status = status
        self.message = message
        self.success = success
        self.code = code
        self.result = result

    def serialize(self) -> t.Optional[dict]:
        return {
            'timestamp': self.timestamp,
            'status': self.status,
            'code': self.code,
            'message': self.message,
            'success': self.success,
            'result': serialize(self.result)
        }

    def deserialize(self, data: dict) -> t.Optional[object]:
        if data:
            self.timestamp = data.get('timestamp')
            self.status = data.get('status')
            self.message = data.get('message')
            self.success = data.get('success')
            self.code = data.get('code')
            self.result = data.get('result')
        return self


def response_success(result: t.Optional[object] = None, message: t.Optional[str] = None) -> ApiResponse:
    return ApiResponse(success=True, message=message, result=result)


def response_error(message: t.Optional[str] = None,
                   status: t.Optional[int] = 400,
                   code: t.Optional[int] | t.Optional[str] = "400",
                   result: t.Optional[object] = None) -> ApiResponse:
    return ApiResponse(success=False, status=status, code=code, message=message, result=result)
